package com.maiyuren.dict_page_view_plugin.dictpageview;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import com.maiyuren.dict_page_view_plugin.DictPageViewPlugin;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Picture;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;

import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.viewpager.widget.PagerAdapter;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import io.flutter.plugin.common.MethodChannel;

public class DictPageViewAdapter extends PagerAdapter {
    Integer _id = 0;
    public int MAX_LENGTH = 0;

    DictPageViewAdapter(List<Map<String, Object>> info, Integer id) {
        _id = id;

        _info = info;
        MAX_LENGTH = _info.size(); // * 1000;
        for(int i = 0; i < _info.size(); ++i) {
            DictPageViewAdapter.ViewInfo vi = new DictPageViewAdapter.ViewInfo();
            vi.info_ = _info.get(i);
            vi.index_ = i;
            dictViews_.add(vi);
        }

        WebView.enableSlowWholeDocumentDraw();
    }
    public List<Map<String, Object>> _info = null;

    @Override
    public int getCount() {
        if (_info != null) return MAX_LENGTH;
        return 0;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    public void loadUrl(int tabIndex, String url) {
        dictViews_.get(tabIndex).showResult(url);
    }
    public byte[] takePhoto(int tabIndex) {
        try {
            return dictViews_.get(tabIndex).takePhoto();
        } catch (Exception ex) {
            return null;
        }
    }


    class ViewInfo {
        public LinearLayout view_;
        public Map<String,Object> info_ = null;
        public Integer index_ = 0;

        public void init(LinearLayout view) {
            view_ = view;
            TextView titleLabel = view_.findViewWithTag("title");

            if(titleLabel != null)
                titleLabel.setText(info_.get("name").toString());

            WebView webView = view_.findViewWithTag("webView");

            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDefaultTextEncodingName("UTF-8");
            //允许webview对文件的操作
            webSettings.setAllowUniversalAccessFromFileURLs(true);
            webSettings.setAllowFileAccess(true);
            webSettings.setAllowFileAccessFromFileURLs(true);

            // 缩放
            // 设置可以支持缩放
            webSettings.setSupportZoom(true);
            // 设置出现缩放工具
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(false);

            //扩大比例的缩放
            // webSettings.setUseWideViewPort(true);
            //自适应屏幕
//            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//            webSettings.setLoadWithOverviewMode(true);

            webSettings.setDomStorageEnabled(true);

            webView.setWebViewClient(new WebViewClient() {
                @Override
                public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest req) {
                    DictCallbackResult callback = new DictCallbackResult();
                    try {
                        Map<String, Object> param = new HashMap<>();
                        param.put("id", _id);
                        param.put("tabIndex", index_);
                        param.put("url", req.getUrl().toString());
                        Object r = utils.invokeMethodAndWaitResult(
                                DictPageViewPlugin.channel,
                                "shouldInterceptRequest",
                                utils.map2string(param),
                                callback);

                        byte[] buf = (byte[])r;
                        if (buf != null) {
                            InputStream stream  = new ByteArrayInputStream(buf);
                            return new WebResourceResponse(
                                    "application/octet-stream",
                                    "UTF-8",
                                    stream
                            );
                        }
                    }catch (Exception ex) {}
                    return super.shouldInterceptRequest(view, req);
                }


                @Override
                public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                    if (request.isRedirect()) return false;


                    String url = request.getUrl().toString();

                    // web網頁，且不是我維護的，不處理
                    // 解決問題：在訪問某些網頁時，有些網頁指定refers，會導致加載失敗
                    // 故不作通信處理
                    if ("web".equals(info_.get("type")) && !url.contains("maiyuren.com")) {
                        return false;
                    }

                    Map<String, Object> param = new HashMap<>();
                    param.put("id", _id);
                    param.put("tabIndex", index_);
                    param.put("url", url);

                    DictPageViewPlugin.channel.invokeMethod("shouldOverrideUrlLoading", utils.map2string(param), new MethodChannel.Result() {
                        @Override
                        public void success(@Nullable Object obj) {
                            if (obj == null) {
                                view.loadUrl(url);
                                return;
                            }

                            boolean b = (boolean) obj;
                            if (!b) {
                                view.loadUrl(url);
                            }
                        }

                        @CallSuper
                        @Override
                        public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
                        }

                        @CallSuper
                        @Override
                        public void notImplemented() {


                        }
                    });

                    return true;
                }
            });
            webView.setBackgroundColor(0xffdddddd);

            webView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
                    // 如果是图片类型或者是带有图片链接的类型
                    if (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE ||
                            hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                        // 弹出保存图片的对话框
                        String url = hitTestResult.getExtra();//获取图片链接
                        Map<String, Object> param = new HashMap<>();
                        param.put("id", _id);
                        param.put("tabIndex", index_);
                        param.put("url", url);
                        DictPageViewPlugin.channel.invokeMethod("shareImage", utils.map2string(param), new MethodChannel.Result() {
                            @Override
                            public void success(@Nullable Object obj) {
                            }

                            @CallSuper
                            @Override
                            public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
                            }

                            @CallSuper
                            @Override
                            public void notImplemented() {


                            }
                        });
                        return true;
                    }
                    return false;//保持长按可以复制文字
                }
            });

            webView.setDrawingCacheEnabled(true); // 启用绘图缓存
        }

        public void showResult(String toShow) {
            if (view_ == null) return;
            WebView webView = view_.findViewWithTag("webView");
            webView.loadUrl(toShow);
        }

        public byte[] takePhoto() throws IOException {
            WebView webView = view_.findViewWithTag("webView");

            Picture snapShot = webView.capturePicture();
            Bitmap bitmap = Bitmap.createBitmap(snapShot);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // 保存Bitmap到文件
            outputStream.flush();
            outputStream.close();
            bitmap.recycle();
            return outputStream.toByteArray();
        }
    }

    private List<DictPageViewAdapter.ViewInfo> dictViews_ = new Vector<>();

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        int truePos = position % _info.size();
        LinearLayout view = dictViews_.get(truePos).view_;
        if (view == null) {
            view = new LinearLayout(container.getContext());
            ViewGroup.LayoutParams layoutParam = new LinearLayout.LayoutParams(
                    MATCH_PARENT,
                    MATCH_PARENT
            );
            view.setOrientation(LinearLayout.VERTICAL);
            view.setLayoutParams(layoutParam);

            TextView titleTextView = new TextView(container.getContext());
            titleTextView.setTextSize(18);
            titleTextView.setTag("title");
            titleTextView.setTextColor(0xff000000);
            titleTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER);
            view.addView(titleTextView, MATCH_PARENT, utils.dip2px(container.getContext(), 44));


            DictActionWebView webView = new DictActionWebView(container.getContext(), _id, truePos);
            webView.setTag("webView");
            LinearLayout.LayoutParams webViewLayourParam = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
            webViewLayourParam.weight = 1;
            webView.setLayoutParams(webViewLayourParam);
            view.addView(webView);

            dictViews_.get(truePos).init(view);
        }
        container.addView(view);
        return view;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View)object);
    }
}
